package com.hmjk.health.card;

import java.util.Calendar;

import com.hmjk.health.HealthApp;
import com.hmjk.health.R;
import com.hmjk.health.background.DataManager;
import com.hmjk.health.util.ACareReminder;
import com.hmjk.health.util.AReminder;
import com.hmjk.health.util.ReminderList;
import com.hmjk.health.util.reminderTime;
import com.hmjk.health.views.SwitchButton;
import com.hmjk.health.views.SwitchButton.OnChangeListener;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;

public class ReminderActivity extends Activity implements OnClickListener{
	private HealthApp mApp = null;	
	private String mDid;
	private LinearLayout r1titleLayout,r2titleLayout,r3titleLayout;
	private LinearLayout r1ContentLayout,r2ContentLayout,r3ContentLayout;
	
	private ImageView r1LeftTitleImg,r2LeftTitleImg,r3LeftTitleImg;
	private ImageView leftTitleImgArr[] = new ImageView[3]; 
	private ImageView r1RightTitleImg,r2RightTitleImg,r3RightTitleImg;
	private TextView r1TitleTxt,r2TitleTxt,r3TitleTxt;
	private TextView r1TitleTip,r2TitleTip,r3TitleTip;
	
	private EditText r1contentEdit,r2contentEdit,r3contentEdit;
	private EditText contentEditArr[] = new EditText[3]; 	
	private TextView r1timeTxt,r2timeTxt,r3timeTxt;
	private TextView timeTxtArr[] = new TextView[3]; 		
	private TextView r1repeatTxt,r2repeatTxt,r3repeatTxt;
	private TextView repeatTxtArr[] = new TextView[3]; 	
	private SwitchButton r1Swi,r2Swi,r3Swi;
	private SwitchButton swiArr[] = new SwitchButton[3];
	private Button r1ComitBut,r2ComitBut,r3ComitBut;
	private Button rCommitButArr[] = new Button[3];
    private TextView r1StateTxt,r2StateTxt,r3StateTxt;	
    private TextView rStateTxtArr[] = new TextView[3];
    private TextView rTitleTip[] = new TextView[3];
    

	private ACareReminder rem1;
	private ACareReminder rem2;
	private ACareReminder rem3;
	private ACareReminder remArray[] = new ACareReminder[3];
	private boolean isAdmin = false;
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
	
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		mApp = (HealthApp)getApplication();
		Intent i = getIntent();
		mDid = i.getStringExtra("tid");
		isAdmin = i.getBooleanExtra("isAdmin", false);
		
		rem1 = new ACareReminder(mDid,0);
		rem2 = new ACareReminder(mDid,0);
		rem3 = new ACareReminder(mDid,0);
		remArray[0] = rem1;
		remArray[1] = rem2;
		remArray[2] = rem3;
		
		setContentView(R.layout.remind);
		
		ImageButton back = (ImageButton)findViewById(R.id.back);
		back.setOnClickListener(this);
		
		r1titleLayout = (LinearLayout)findViewById(R.id.rLayoutTitle1);
		r2titleLayout = (LinearLayout)findViewById(R.id.rLayoutTitle2);
		r3titleLayout = (LinearLayout)findViewById(R.id.rLayoutTitle3);
		
		r1ContentLayout = (LinearLayout)findViewById(R.id.rLayoutContent1);
		r2ContentLayout = (LinearLayout)findViewById(R.id.rLayoutContent2);
		r3ContentLayout = (LinearLayout)findViewById(R.id.rLayoutContent3);		
		
		/**********reminder 1***********/
		r1LeftTitleImg = (ImageView)r1titleLayout.findViewById(R.id.lefImg);
		r1RightTitleImg = (ImageView)r1titleLayout.findViewById(R.id.rightImg);
		r1TitleTxt = (TextView)r1titleLayout.findViewById(R.id.tit);
		r1TitleTip = (TextView)r1titleLayout.findViewById(R.id.overdue);
			
		r1contentEdit = (EditText)r1ContentLayout.findViewById(R.id.content_edit);
		r1timeTxt = (TextView)r1ContentLayout.findViewById(R.id.timeTxt);		
		//r1validTimeTxt = (TextView)r1ContentLayout.findViewById(R.id.validTimeTxt);
		r1repeatTxt = (TextView)r1ContentLayout.findViewById(R.id.repeatTxt);
		r1ComitBut =(Button)r1ContentLayout.findViewById(R.id.commit_but);
		

		r1titleLayout.setOnClickListener(this);
		r1contentEdit.setOnClickListener(this);
		r1contentEdit.addTextChangedListener(new TextWatcher(){
			@Override
			public void afterTextChanged(Editable arg0) {
				// TODO Auto-generated method stub
				rem1.tipContent = r1contentEdit.getText().toString();
			}
			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
				// TODO Auto-generated method stub
				
			}
			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				// TODO Auto-generated method stub
				
			}
			
		});
		r1timeTxt.setOnClickListener(this);
		//r1validTimeTxt.setOnClickListener(this);
		r1repeatTxt.setOnClickListener(this);
		r1ComitBut.setOnClickListener(this);
		r1timeTxt.setTag(rem1);
		r1repeatTxt.setTag(rem1);	
		r1ComitBut.setTag(rem1);
		r1Swi = (SwitchButton)r1ContentLayout.findViewById(R.id.remSwi);
		r1Swi.setOnChangeListener(new OnChangeListener() {

			@Override
			public void onChange(SwitchButton sb, boolean state) {
				// TODO Auto-generated method stub
				if(state)
				{
				rem1.isopen = 0;
				r1LeftTitleImg.setImageResource(R.drawable.addr_date_grey);
				}
				else
				{
				rem1.isopen = 1;
				r1LeftTitleImg.setImageResource(R.drawable.addr_date_yellow);
				}
			}  

        });		
		if(r1Swi.getFlage())
			rem1.isopen = 0;
		else
			rem1.isopen = 1;
		r1StateTxt = (TextView) r1ContentLayout.findViewById(R.id.remSwiTitle);
		

		
		/**********reminder 2***********/
		r2LeftTitleImg = (ImageView)r2titleLayout.findViewById(R.id.lefImg);
		r2RightTitleImg = (ImageView)r2titleLayout.findViewById(R.id.rightImg);
		r2TitleTxt = (TextView)r2titleLayout.findViewById(R.id.tit);
		r2TitleTxt.setText(R.string.Reminder_2);
		r2TitleTip = (TextView)r2titleLayout.findViewById(R.id.overdue);
			
		r2contentEdit = (EditText)r2ContentLayout.findViewById(R.id.content_edit);
		r2timeTxt = (TextView)r2ContentLayout.findViewById(R.id.timeTxt);
		//r2validTimeTxt = (TextView)r2ContentLayout.findViewById(R.id.validTimeTxt);
		r2repeatTxt = (TextView)r2ContentLayout.findViewById(R.id.repeatTxt);
		r2ComitBut =(Button)r2ContentLayout.findViewById(R.id.commit_but);

		r2titleLayout.setOnClickListener(this);
		r2contentEdit.setOnClickListener(this);
		r2contentEdit.addTextChangedListener(new TextWatcher(){
			@Override
			public void afterTextChanged(Editable arg0) {
				// TODO Auto-generated method stub
				rem2.tipContent = r2contentEdit.getText().toString();
			}
			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
				// TODO Auto-generated method stub
				
			}
			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				// TODO Auto-generated method stub
				
			}
			
		});		
		r2timeTxt.setOnClickListener(this);
		//r2validTimeTxt.setOnClickListener(this);
		r2repeatTxt.setOnClickListener(this);
		r2ComitBut.setOnClickListener(this);
		r2timeTxt.setTag(rem2);
		r2repeatTxt.setTag(rem2);	
		r2ComitBut.setTag(rem2);		
		r2Swi = (SwitchButton)r2ContentLayout.findViewById(R.id.remSwi);
		r2Swi.setOnChangeListener(new OnChangeListener() {

			@Override
			public void onChange(SwitchButton sb, boolean state) {
				// TODO Auto-generated method stub
				if(state)
				{
				rem2.isopen = 0;
				r2LeftTitleImg.setImageResource(R.drawable.addr_date_grey);
				}
				else
				{
				rem2.isopen = 1;
				r2LeftTitleImg.setImageResource(R.drawable.addr_date_yellow);
				}
			}  

        });
		if(r2Swi.getFlage())
			rem2.isopen = 0;
		else
			rem2.isopen = 1;		
		r2StateTxt = (TextView) r2ContentLayout.findViewById(R.id.remSwiTitle);
		
		/**********reminder 3***********/
		r3LeftTitleImg = (ImageView)r3titleLayout.findViewById(R.id.lefImg);
		r3RightTitleImg = (ImageView)r3titleLayout.findViewById(R.id.rightImg);
		r3TitleTxt = (TextView)r3titleLayout.findViewById(R.id.tit);
		r3TitleTxt.setText(R.string.Reminder_3);	
		r3TitleTip = (TextView)r3titleLayout.findViewById(R.id.overdue);
		
		r3contentEdit = (EditText)r3ContentLayout.findViewById(R.id.content_edit);
		r3timeTxt = (TextView)r3ContentLayout.findViewById(R.id.timeTxt);
		//r3validTimeTxt = (TextView)r3ContentLayout.findViewById(R.id.validTimeTxt);
		r3repeatTxt = (TextView)r3ContentLayout.findViewById(R.id.repeatTxt);
		r3ComitBut =(Button)r3ContentLayout.findViewById(R.id.commit_but);

		r3titleLayout.setOnClickListener(this);
		r3contentEdit.setOnClickListener(this);
		r3contentEdit.addTextChangedListener(new TextWatcher(){
			@Override
			public void afterTextChanged(Editable arg0) {
				// TODO Auto-generated method stub
				rem3.tipContent = r3contentEdit.getText().toString();
			}
			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
				// TODO Auto-generated method stub
				
			}
			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				// TODO Auto-generated method stub
				
			}
			
		});		
		r3timeTxt.setOnClickListener(this);
		r3timeTxt.setTag(rem3);
		r3repeatTxt.setTag(rem3);	
		r3ComitBut.setTag(rem3);		
		//r3validTimeTxt.setOnClickListener(this);
		r3repeatTxt.setOnClickListener(this);
		r3ComitBut.setOnClickListener(this);
		r3Swi = (SwitchButton)r3ContentLayout.findViewById(R.id.remSwi);
		r3Swi.setOnChangeListener(new OnChangeListener() {

			@Override
			public void onChange(SwitchButton sb, boolean state) {
				// TODO Auto-generated method stub
				if(state)
				{
				rem3.isopen = 0;
				r3LeftTitleImg.setImageResource(R.drawable.addr_date_grey);
				}
				else
				{
				rem3.isopen = 1;
				r3LeftTitleImg.setImageResource(R.drawable.addr_date_yellow);
				}
			}  

        });
		if(r3Swi.getFlage())
			rem3.isopen = 0;
		else
			rem3.isopen = 1;		
		r3StateTxt = (TextView) r3ContentLayout.findViewById(R.id.remSwiTitle);
		
		leftTitleImgArr[0] = r1LeftTitleImg;
		leftTitleImgArr[1] = r2LeftTitleImg;
		leftTitleImgArr[2] = r3LeftTitleImg;
		contentEditArr[0] = r1contentEdit;	
		contentEditArr[1] = r2contentEdit;		
		contentEditArr[2] = r3contentEdit;	
		timeTxtArr[0] = r1timeTxt;
		timeTxtArr[1] = r2timeTxt;
		timeTxtArr[2] = r3timeTxt;
		repeatTxtArr[0] = r1repeatTxt;
		repeatTxtArr[1] = r2repeatTxt;
		repeatTxtArr[2] = r3repeatTxt;
		swiArr[0] = r1Swi;
		swiArr[1] = r2Swi;
		swiArr[2] = r3Swi;
		rStateTxtArr[0] = r1StateTxt;
		rStateTxtArr[1] = r2StateTxt;
		rStateTxtArr[2] = r3StateTxt;
		rCommitButArr[0] = r1ComitBut;
		rCommitButArr[1] = r2ComitBut;
		rCommitButArr[2] = r3ComitBut;
		rTitleTip[0] = r1TitleTip;
		rTitleTip[1] = r2TitleTip;
		rTitleTip[2] = r3TitleTip;
		
		changeVisabilityByAdmin();
		
		IntentFilter filter = new IntentFilter();
		filter.addAction(DataManager.DATA_UPDATE_ACTION);
		filter.addAction(DataManager.DATA_COMMIT_RESULT);
		registerReceiver(mReceiver, filter);	
		
		if(mApp.getDataManager().refreshData(DataManager.F_CARE_REMINDER, mDid))
		   mApp.showWaitting(this, null);
		else
			checkReminderData();
		
	}
	
	private void changeVisabilityByAdmin()
	{
		if(!this.isAdmin)
		{
			for(int i=0;i<contentEditArr.length;i++)
			   contentEditArr[i].setEnabled(false);
			
			for(int i=0;i<timeTxtArr.length;i++)
				timeTxtArr[i].setEnabled(false);
			
			for(int i=0;i<repeatTxtArr.length;i++)
				repeatTxtArr[i].setEnabled(false);		
			
			for(int i=0;i<swiArr.length;i++)
				swiArr[i].setVisibility(View.GONE);
			
			for(int i=0;i<rStateTxtArr.length;i++)
			{
				rStateTxtArr[i].setVisibility(View.VISIBLE);
			}
			
			for(int i=0;i<rCommitButArr.length;i++)
				rCommitButArr[i].setVisibility(View.GONE);
			
		}
					
	}
	
	
	private void checkReminderData()
	{
		

		
		String[] args = new String[1];
		args[0] = mDid;
		ReminderList list = (ReminderList) mApp.getDataManager().checkData(DataManager.F_CARE_REMINDER, args);
		
		if(list != null)
		{
			for(int i=0;i<remArray.length;i++)
			{
				remArray[i].tipContent = "";
				remArray[i].time.Hour = -1;
			    remArray[i].time.Min = -1;
				remArray[i].isopen = 1;	
				remArray[i].time.repeat = reminderTime.WEEK_MARK;
				remArray[i].time.single = reminderTime.SINGLE_MARK;
			}
			
			for(int i = 0;i<list.length();i++)
			{
					ACareReminder rem = (ACareReminder) list.getReminder(i);
				    int j = rem.Index-1;
                    remArray[j].setByReminder(rem);
			}
		}
		updateRemsDisplay();
	}
	
	private int comitEmptyIndex = -1;
	
	private void commitEmpty()
	{
		ACareReminder aR = new ACareReminder(mDid,0);
		aR.tipContent = "";
		aR.time.Hour = 8;
		aR.time.Min = 0;
		aR.isopen = 1;	
		aR.opt = AReminder.NEW_OFF_OP;
		aR.time.repeat = reminderTime.WEEK_MARK;
		aR.time.single = reminderTime.SINGLE_MARK;
		mApp.getDataManager().commitData(DataManager.F_CARE_REMINDER, aR);
		comitEmptyIndex ++;
	}
	
	private BroadcastReceiver mReceiver = new BroadcastReceiver(){
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if(action.equals(DataManager.DATA_UPDATE_ACTION)){
				String t = intent.getStringExtra("type");	
				if(t.equals(DataManager.F_CARE_REMINDER))
				{
					String state = intent.getStringExtra("state");
					if(state.equalsIgnoreCase("AC"))
					{
						comitEmptyIndex = 0;
						commitEmpty();
					}
					else
					{	
						comitEmptyIndex = -1;
					mApp.dismissWaiting();
					boolean update = intent.getBooleanExtra("update", false);
					if(update)
					{
						checkReminderData();    
					}
					}
					
				}
								
			}			
			else if(action.equals(DataManager.DATA_COMMIT_RESULT))
			{
				String t = intent.getStringExtra("type");
				String tid = intent.getStringExtra("tid");

				if(t.equals(DataManager.F_CARE_REMINDER) && tid.equals(mDid)){
				String state = intent.getStringExtra("state");
				int code = intent.getIntExtra("code", 400);
				if(code != 200){
					if(comitEmptyIndex >= 0)
					{
						comitEmptyIndex = -1;
						mApp.dismissWaiting();
						mApp.showAlertDialog(ReminderActivity.this, getResources().getString(R.string.network_err),new OnClickListener()
						{

							@Override
							public void onClick(View arg0) {
								// TODO Auto-generated method stub
								finish();
								
							}});
					}
					else
					{
					mApp.dismissWaiting();
					mApp.showAlertDialog(ReminderActivity.this, R.string.commit_err);
					}

				}else if(state.equals("00") == false){
					if(comitEmptyIndex >= 0)
					{
						comitEmptyIndex = -1;
						mApp.dismissWaiting();
						mApp.showAlertDialog(ReminderActivity.this, getResources().getString(R.string.network_err),new OnClickListener()
						{

							@Override
							public void onClick(View arg0) {
								// TODO Auto-generated method stub
								finish();
								
							}});
					}
					else
					{					
					mApp.dismissWaiting();
					mApp.showAlertDialog(ReminderActivity.this, R.string.commit_err);	
					}
				}else{
					if(comitEmptyIndex >= 0)
					{
						if(comitEmptyIndex < 3)
						 commitEmpty();
						else
						{
							comitEmptyIndex = -1;
							mApp.dismissWaiting();
							checkReminderData();
						}
							
					}
					else
					{
					mApp.dismissWaiting();
					//mApp.showAlertDialog(ReminderActivity.this, R.string.commit_ok);
					checkReminderData();
					mApp.showAlertDialog(ReminderActivity.this, getResources().getString(R.string.commit_ok), R.string.ok, new OnClickListener() {
						
						@Override
						public void onClick(View arg0) {
							// TODO Auto-generated method stub
							reminderLayoutSpread(r1ContentLayout,r1RightTitleImg,false);
							reminderLayoutSpread(r2ContentLayout,r2RightTitleImg,false);
							reminderLayoutSpread(r3ContentLayout,r3RightTitleImg,false);
							
						}
					});
					}
				}	
				}
			}
		}
	};
	
	private boolean isReminderOverdue(ACareReminder rem)
	{
		boolean ret = false;
		long upTime = rem.update_time;
		int rH = rem.time.Hour;
		int rM = rem.time.Min;
		
		Calendar c = Calendar.getInstance();
		c.setTimeInMillis(upTime);
		int uH = c.get(Calendar.HOUR_OF_DAY);
		int uM = c.get(Calendar.MINUTE);
		long distance = 0,now;
		now = System.currentTimeMillis();
		
		
	    if((rH*60+rM) > (uH*60 + uM))
	    {
	    	c.set(Calendar.HOUR_OF_DAY, rH);
	    	c.set(Calendar.MINUTE,rM);	    	
	    }
	    else
	    {
	    	int day = c.get(Calendar.DAY_OF_YEAR);	
	    	c.set(Calendar.HOUR_OF_DAY, rH);
	    	c.set(Calendar.MINUTE,rM);	
	    	c.set(Calendar.DAY_OF_YEAR, day+1);
	    }
	    distance = now - c.getTimeInMillis(); 
	    
	    if(distance > 0)
	    	ret = true;
	    else
	    	ret = false;
	    
		return ret;
	}
	
	private void updateRemsDisplay()
	{
		for(int i=0;i<3;i++)
		{
			if(remArray[i].isopen == 0)
				leftTitleImgArr[i].setImageResource(R.drawable.addr_date_yellow);	
			else
				leftTitleImgArr[i].setImageResource(R.drawable.addr_date_grey);		
			

			contentEditArr[i].setText(remArray[i].getTip());
			
			if(remArray[i].time.Hour != -1 && remArray[i].time.Min != -1)
			    timeTxtArr[i].setText(String.format("%02d:%02d", remArray[i].time.Hour,remArray[i].time.Min));
			else
				timeTxtArr[i].setText("");
			
			String s = "";
			
            boolean isSingle = false;
            for(int j = 0;j<7;j++)
            {
            	if(remArray[i].time.getWeekRepeat(j) && remArray[i].time.getWeekSingle(j))
            	{
            		isSingle = true;
            		break;
            	}
            }
            
			if(isSingle)
			{
				s = getResources().getString(R.string.single);
				if(isReminderOverdue(remArray[i]))
				{
					rTitleTip[i].setText(R.string.overdue);
				}
				else
				{
					rTitleTip[i].setText("");
				}
								
			}
			else
			{
			    if((remArray[i].time.repeat & reminderTime.MON) != 0)
				s = s+getResources().getString(R.string.monday)+" ";
			    if((remArray[i].time.repeat & reminderTime.TUE) != 0)
				s = s+getResources().getString(R.string.tuesday)+" ";
			    if((remArray[i].time.repeat & reminderTime.WEN) != 0)
				s = s+getResources().getString(R.string.wednesday)+" ";
			    if((remArray[i].time.repeat & reminderTime.THR) != 0)
				s = s+getResources().getString(R.string.thursday)+" ";
			    if((remArray[i].time.repeat & reminderTime.FRI) != 0)
				s = s+getResources().getString(R.string.friday)+" ";
			    if((remArray[i].time.repeat & reminderTime.SAT) != 0)
				s = s+getResources().getString(R.string.saturday)+" ";
			    if((remArray[i].time.repeat & reminderTime.SUN) != 0)
				s = s+getResources().getString(R.string.Sunday)+" ";
			    
			    rTitleTip[i].setText("");
			}
			repeatTxtArr[i].setText(s);
			
			if(remArray[i].isopen == 0)
			{	
			  swiArr[i].setFlage(true);
			  rStateTxtArr[i].setText(R.string.fence_open);
			}
			else
			{
			  swiArr[i].setFlage(false);
			  rStateTxtArr[i].setText(R.string.fence_closed);
			}
				
		}
	}
	
	private void reminderLayoutSpread(LinearLayout ll, ImageView titleImg, boolean isSpread)
	{
		if(isSpread)
		{
			Animation in = AnimationUtils.loadAnimation(this, R.anim.opendown);
			ll.setVisibility(View.VISIBLE);
			ll.startAnimation(in);			
			titleImg.setImageResource(R.drawable.collect);			
		}
		else
		{
			//Animation out = AnimationUtils.loadAnimation(this, R.anim.closeup);
			ll.setVisibility(View.GONE);
			//ll.startAnimation(out);	
			titleImg.setImageResource(R.drawable.spread);			
		}
	}

	@Override
	protected void onDestroy() {
		unregisterReceiver(mReceiver);
		super.onDestroy();
	}	
	
	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.back:{
			finish();
		}break;
		
		case R.id.rLayoutTitle1:
		{			
			if(r1ContentLayout.getVisibility() == View.GONE)
            {
				reminderLayoutSpread(r1ContentLayout,r1RightTitleImg,true);
				reminderLayoutSpread(r2ContentLayout,r2RightTitleImg,false);
				reminderLayoutSpread(r3ContentLayout,r3RightTitleImg,false);
			}else{
				reminderLayoutSpread(r1ContentLayout,r1RightTitleImg,false);
			}			
		}
		break;
		
		case R.id.rLayoutTitle2:
		{
			if(r2ContentLayout.getVisibility() == View.GONE)
            {
				reminderLayoutSpread(r2ContentLayout,r2RightTitleImg,true);
				reminderLayoutSpread(r1ContentLayout,r1RightTitleImg,false);
				reminderLayoutSpread(r3ContentLayout,r3RightTitleImg,false);
			}else{
				reminderLayoutSpread(r2ContentLayout,r2RightTitleImg,false);
			}						
		}
		break;
		case R.id.rLayoutTitle3:
		{
			if(r3ContentLayout.getVisibility() == View.GONE)
            {
				reminderLayoutSpread(r3ContentLayout,r1RightTitleImg,true);
				reminderLayoutSpread(r2ContentLayout,r2RightTitleImg,false);
				reminderLayoutSpread(r1ContentLayout,r1RightTitleImg,false);
			}else{
				reminderLayoutSpread(r3ContentLayout,r3RightTitleImg,false);
			}						
		}
		break;	
		
		case R.id.timeTxt:
		{
			final TextView txtV = (TextView)v;
			final ACareReminder rem = (ACareReminder) txtV.getTag();
			Calendar c=Calendar.getInstance();
            Dialog dialog=new TimePickerDialog(
                this, 
                new TimePickerDialog.OnTimeSetListener(){
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                    	//txtV.setText(hourOfDay+":"+minute);
                    	txtV.setText(String.format("%02d:%02d", hourOfDay,minute));
                    	rem.time.Hour = hourOfDay;
                    	rem.time.Min = minute;
                    }
                },
                c.get(Calendar.HOUR_OF_DAY),
                c.get(Calendar.MINUTE),
                false
            );	
            
            dialog.show();
		}
		break;
		
		case R.id.repeatTxt:
		{
			final TextView txtV = (TextView)v;
			final ACareReminder rem = (ACareReminder) txtV.getTag();			
			final boolean selected[] = {false,false,false,false,false,false,false,false};
			final String[] items = new String[8];//{"星期一","星期二","星期三","星期四","星期五","星期六","星期日",};
			
			items[0] = getResources().getString(R.string.monday);
			items[1] = getResources().getString(R.string.tuesday);
			items[2] = getResources().getString(R.string.wednesday);
			items[3] = getResources().getString(R.string.thursday);
			items[4] = getResources().getString(R.string.friday);
			items[5] = getResources().getString(R.string.saturday);
			items[6] = getResources().getString(R.string.Sunday);
			items[7] = getResources().getString(R.string.single);
			
			for(int i=0;i<7;i++)
			{								
				selected[i] = rem.time.getWeekRepeat(i);
				if(selected[i])
				{
					selected[7] = rem.time.getWeekSingle(i);
					if(selected[7])
						selected[i] = false;
				}
			}
			//selected[7] = rem.time.getWeekSingle(1);
			
            Builder builder = new AlertDialog.Builder(this);  
            builder.setTitle(R.string.remind_repeat);  
            //builder.setIcon(R.drawable.basketball);  
            DialogInterface.OnMultiChoiceClickListener mutiListener =   
                new DialogInterface.OnMultiChoiceClickListener() {  
                      
                    @Override  
                    public void onClick(DialogInterface dialogInterface,   
                            int which, boolean isChecked) {  
                        selected[which] = isChecked;  
                    }  
                };  
            builder.setMultiChoiceItems(items, selected, /*mutiListener*/null);  
            DialogInterface.OnClickListener btnListener =   
                new DialogInterface.OnClickListener() {  
                    @Override  
                    public void onClick(DialogInterface dialogInterface, int which) {  
                        String selectedStr = "";  
                        if(selected[7])
                        {
                        	selectedStr = items[7];
                        	Calendar c = Calendar.getInstance();
                        	int w = c.get(Calendar.DAY_OF_WEEK);
                        	int cHour = c.get(Calendar.HOUR_OF_DAY);
                        	int cMin = c.get(Calendar.MINUTE);
                        	
                        	float f1 = (float)cHour + (float)cMin/60;
                        	float f2 = (float)rem.time.Hour + (float)rem.time.Min/60;
                        	
                        	if(f1 <= f2)
                        	{
                        		w = (w+5)%7;
                        	}
                        	else
                        	{
                        		w++;
                        		w = (w+5)%7;
                        	}
                        	
                            for(int i=0; i<7; i++) {  
                                rem.time.setWeekRepeat(i, false, true);
                            } 
                            
                        	rem.time.setWeekRepeat(w, true, true);
                        	
                       	
                        	
                        }
                        else
                        {	
                        for(int i=0; i<7; i++) {  
                            if(selected[i] == true) {  
                                selectedStr = selectedStr + " " +  
                                		items[i];  
                                rem.time.setWeekRepeat(i, true, false);
                            } 
                            else
                            	rem.time.setWeekRepeat(i, false, false);
                        } 
                        }
                        
                        txtV.setText(selectedStr); 
                        
                    }  
                };  
            builder.setPositiveButton(getResources().getString(R.string.ok), btnListener);  
            AlertDialog dialog = builder.create();  		
            dialog.show();
            final ListView lv = dialog.getListView();
            //OnItemClickListener 
            
            lv.setOnItemClickListener(new OnItemClickListener(){

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					// TODO Auto-generated method stub
					
				   selected[arg2] = !selected[arg2];	
                   if(arg2 == 7 && selected[7] == true)
                   {
                	   for(int i=0;i<7;i++)
                	   {
                	     lv.setItemChecked(i, false);
                	     selected[i] = false;
                	   }
                   }
                   
                   if(arg2 != 7 && selected[arg2] == true)
                   {
                	  lv.setItemChecked(7, false);
                	  selected[7] = false;
                   }					
				}
            	
            });

		}
		break;
		
		case R.id.commit_but:
		{
			ACareReminder rem = (ACareReminder) v.getTag();
			
			if(rem.Index == 0)
			{	
				if(rem.isopen == 0)
				   rem.opt = AReminder.NEW_OPEN_OP;
				else
				   rem.opt = AReminder.NEW_OFF_OP;
			}
			else
			{
				if(rem.isopen == 0)
					   rem.opt = AReminder.MODIFY_OPEN_OP;
					else
					   rem.opt = AReminder.MODIFY_OFF_OP;				
			}
			
			
			if(rem.time.Hour == -1 || rem.time.Min == -1)
			{
				mApp.showAlertDialog(this, R.string.time_not_set);
			}
			else if(rem.time.repeat == reminderTime.WEEK_MARK)
			{
				mApp.showAlertDialog(this, R.string.repeat_not_set);
			}
			else if(rem.tipContent == null || rem.tipContent.length() == 0)
			{
				mApp.showAlertDialog(this, R.string.content_not_set);
			}
			else	
			{

				if(mApp.getDataManager().commitData(DataManager.F_CARE_REMINDER, rem)){				
					mApp.showWaitting(this, new DialogInterface.OnCancelListener(){
						@Override
						public void onCancel(DialogInterface arg0) {
							// TODO					
						}	        	
			        });
				}
			}
		}
		break;
		}
		
		
		
	}	
}